package com.mabs.ground.client.common;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.user.client.Window;
import com.mabs.ground.shared.DataResponseBean;
import com.mabs.ground.shared.model.ModelBean;

/**
 * @author <a href="Email: mohamedarbi.benslimane@allence-tunisie.com">Ben
 *         Slimane Arbi</a>
 * @version 1.0
 * @since 1.0 - 25 juil. 2014 - 19:05:52
 */
public abstract class MyAbstractActivity extends AbstractActivity {
	private ClientFactory clientFactory;

	public MyAbstractActivity(ClientFactory clientFactory) {
		this.clientFactory = clientFactory;
	}

	public ClientFactory getClientFactory() {
		return clientFactory;
	}

	public PlaceController getPlaceController() {
		return this.clientFactory.getPlaceController();
	}

	protected <M extends ModelBean> void requestData(String url, String data,
			MyRequestCallback<M> myRequestCallback) {
		try {
			getClientFactory().getJsonRequest(url, data, myRequestCallback);
		} catch (RequestException e) {
			Window.alert("error");
		}
	}

	protected abstract class MyRequestCallback<M extends ModelBean> implements
			RequestCallback {
		private Class<DataResponseBean<M>> clazz;

		public MyRequestCallback(Class<DataResponseBean<M>> clazz) {
			this.clazz = clazz;
		}

		public void onResponseReceived(Request request, Response response) {
			DataResponseBean<M> m = null;
			if (200 == response.getStatusCode()) {
				m = getClientFactory().deserializeFromJson(response.getText(),
						clazz);
			} else {
				Window.alert("Couldn't retrieve JSON ("
						+ response.getStatusText() + ")");
			}
			onResponseReceivedDo(m);
		}

		public abstract void onResponseReceivedDo(DataResponseBean<M> resp);

		public void onError(Request request, Throwable exception) {
			Window.alert("error");
		}

	}
}